package com.ywy.schedules;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ywy.entity.Post;
import com.ywy.service.PostService;
import com.ywy.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 定时把缓存中的阅读量同步到数据库中
 *
 * @author ywy
 * @date 2021/12/27 9:42
 */
@Slf4j
@Component
public class ViewCountSyncTask {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PostService postService;

    /**
     * 阅读量同步任务
     * 每天2点同步
     */
    @Scheduled(cron = "0 0 2 * * ?")
//    @Scheduled(cron = "0 0/1 * * * *")
    public void postViewCountSync() {
        log.info("ViewCountSyncTask----->同步文章阅读量开始");

        // 从缓存中查出需要更新的文章
        Set<String> keys = redisTemplate.keys("rank_post:*");
        // 获取需要更新的文章的id
        List<String> ids = new ArrayList<>();
        for (String key : keys) {
            if (redisUtil.hexists(key, "post:viewCount")) {
                ids.add(key.substring("rank_post:".length()));
            }
        }

        if (ids.isEmpty()) {
            return;
        }

        // 获取需要更新的文章信息
        List<Post> posts = postService.list(new QueryWrapper<Post>().in("id", ids));
        posts.forEach(post -> {
            Object viewCount = redisUtil.hget("rank_post:" + post.getId(), "post:viewCount");
            if (viewCount != null) {
                post.setViewCount(Integer.valueOf(viewCount.toString()));
            }
        });

        if (posts.isEmpty()) {
            return;
        }

        // 批量更新文章
        boolean isSuccess = postService.updateBatchById(posts);
        if (isSuccess) {
            // 删除缓存中的阅读数量，防止重复同步
            for (String id : ids) {
                redisUtil.hdel("rank_post:" + id, "post:viewCount");
            }
        }
        log.info("ViewCountSyncTask----->同步文章阅读量完成");
    }
}
